package com.zmj.sy.mom.srv.aps.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;


import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "spring.task.execution.pool")
public class TaskPoolConfig {

    private Integer corePoolSize;

    private Integer maxPoolSize;

    private Integer queueCapacity;

    private Integer keepAliveSeconds;

    private String threadNamePrefix;

    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(corePoolSize == null? 10 : corePoolSize);//核心线程池数
        pool.setMaxPoolSize(maxPoolSize == null? 20 : maxPoolSize); // 最大线程数
        pool.setQueueCapacity(queueCapacity == null? 100 : queueCapacity);//队列容量,当核心线程数达到最大时，新任务会放在队列中排队等待执行
        pool.setKeepAliveSeconds(keepAliveSeconds == null? 60 : keepAliveSeconds);//线程空闲时间
        pool.setAllowCoreThreadTimeOut(false);//核心线程会一直存活，即使没有任务需要执行。（默认false）时，核心线程会超时关闭
        pool.setThreadNamePrefix(threadNamePrefix == null? "TaskExecutor-" : threadNamePrefix);//线程前缀名称
        //默认:AbortPolicy 丢弃任务，抛运行时异常
        //CallerRunsPolicy由调用线程处理该任务
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());

        return pool;
    }
}
